<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\BrandCustomized;
use plugin\admin\app\model\Goods;
use plugin\admin\app\model\GoodsBrand;
use plugin\admin\app\model\UserLevelGoods;
use support\Request;
use support\Response;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 会员等级 
 */
class UserLevelController extends Crud
{
    
    /**
     * @var UserLevel
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserLevel;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('user-level/index');
    }

    public function relation(Request $request): Response
    {
        if ($request->method() == 'POST') {
            $userLevel = $request->get('id');

            $levelGoods = UserLevelGoods::where('level_id', $userLevel)->get()->toArray();
            $goodsIds = array_column($levelGoods, 'goods_id');

            $query = Goods::whereIn('id', $goodsIds);

            $list = $this->doFormat($query, 'normal', 100);

            return $list;
        }

        $id = $request->get('id');
        return view('user-level/relation', [
            'id' => $id,
        ]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('user-level/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('user-level/update');
    }

    protected function formatNormal($items, $total): Response
    {
        $levels = UserLevel::list();
        $levels = array_combine(
            array_column($levels, 'value'),
            array_column($levels, 'name')
        );

        foreach ($items as $key=>$item) {
            $items[$key]['recommend_level_text'] = $levels[$item['recommend_level']] ?? '无';
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    public function get(): Response
    {
        return $this->json(0, 'ok', UserLevel::list());
    }
}
